<template>
  <div class="shifts-container">
    <el-card shadow="never">
      <template #header>
        <div class="header-actions">
          <div class="left-section">
            <h2>班次信息</h2>
            <el-button type="primary" @click="handleAdd">
              <el-icon>
                <Plus />
              </el-icon>
              新增班次
            </el-button>
            <el-button type="danger" @click="goToRules">
              去设置排班规则
            </el-button>
          </div>
          <div class="right-section">
            <el-input placeholder="请输入班次名称" v-model="shiftStore.searchQuery" class="search-input"
              @keyup.enter="handleSearch" clearable @clear="handleSearch">
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </div>
        </div>
      </template>

      <el-table :data="shiftStore.formattedShifts" stripe v-loading="shiftStore.loading">
        <el-table-column prop="shiftName" label="班次名称" />
        <el-table-column prop="startTime" label="开始时间" />
        <el-table-column prop="endTime" label="结束时间" />
        <el-table-column prop="workingHours" label="工作时长(h)" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(row.shiftId!)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination">
        <div class="total">共 {{ shiftStore.pagination.total }} 条</div>
        <el-select v-model="shiftStore.pagination.size" @change="handleSizeChange" style="width: 100px; margin: 0 10px">
          <el-option label="5条/页" :value="5" />
          <el-option label="10条/页" :value="10" />
          <el-option label="20条/页" :value="20" />
        </el-select>
        <el-pagination v-model:current-page="shiftStore.pagination.current" :total="shiftStore.pagination.total"
          :page-size="shiftStore.pagination.size" layout="prev, pager, next" @current-change="handlePageChange" />
        <div class="page-jumper">
          <span>跳至</span>
          <el-input-number v-model="shiftStore.pagination.current" :min="1"
            :max="Math.max(1, Math.ceil(shiftStore.pagination.total / shiftStore.pagination.size))"
            @change="handlePageChange" controls-position="right" style="width: 80px; margin: 0 8px;" />
          <span>页</span>
          <span class="page-total">/ 共 {{ Math.ceil(shiftStore.pagination.total / shiftStore.pagination.size) }}
            页</span>
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑班次' : '新增班次'" width="500px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="班次名称" prop="shiftName" required>
          <el-input v-model="form.shiftName" />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime" required>
          <el-time-picker v-model="form.startTime" format="HH:mm" value-format="HH:mm" placeholder="选择时间" />
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime" required>
          <el-time-picker v-model="form.endTime" format="HH:mm" value-format="HH:mm" placeholder="选择时间" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Search } from "@element-plus/icons-vue";
import { useShiftStore } from "@/stores/schedule/shift";
import type { IShift } from "@/api/schedule/shift";
import { useRouter } from 'vue-router'; 
import { useUserStore } from "@/stores/modules/user";

const shiftStore = useShiftStore();
const dialogVisible = ref(false);
const isEdit = ref(false);
const formRef = ref();

const form = reactive<IShift>({
  shiftName: "",
  startTime: "",
  endTime: "",
  workingHours: 0,
  status: 1,
  deptId: Number(useUserStore().userInfo.staff.deptId),//绑定当前账号对应的部门
});

//去设置排班规则按钮
const router = useRouter();
const goToRules = () => {
  router.push('/scheduling/rules');
};

// 初始化加载
onMounted(() => {
  shiftStore.getShifts();
});

// 新增班次
const handleAdd = () => {
  isEdit.value = false;
  Object.assign(form, {
    shiftName: "",
    startTime: "",
    endTime: "",
    workingHours: 0,
    status: 1,
    deptId: Number(useUserStore().userInfo.staff.deptId),
  });

  // 重置验证
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate();
    }
  });

  dialogVisible.value = true;
};

// 编辑班次
const handleEdit = (row: IShift) => {
  isEdit.value = true;

  const formatTimeForPicker = (timeStr: string) => {
    if (!timeStr) return '';
    return timeStr.substring(0, 5);
  };

  Object.assign(form, {
    ...row,
    startTime: formatTimeForPicker(row.startTime),
    endTime: formatTimeForPicker(row.endTime),
    workingHours: shiftStore.calculateWorkingHours(row.startTime, row.endTime),
  });

  // 重置验证
  nextTick(() => {
    if (formRef.value) {
      formRef.value.clearValidate();
    }
  });

  dialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  try {
    // 验证表单
    await formRef.value.validate();

    // 转换前端时间格式(HH:mm)为后端需要的格式(HH:mm:ss)
    const formatTimeForBackend = (timeStr: string) => {
      if (!timeStr) return null;
      return timeStr.includes(':') ? `${timeStr}:00` : null;
    };

    const submitData = {
      ...form,
      startTime: formatTimeForBackend(form.startTime),
      endTime: formatTimeForBackend(form.endTime),
      workingHours: shiftStore.calculateWorkingHours(
        form.startTime ? `${form.startTime}:00` : '',
        form.endTime ? `${form.endTime}:00` : ''
      )
    };

    if (isEdit.value) {
      await shiftStore.editShift(submitData as IShift);
      ElMessage.success("更新班次成功");
    } else {
      await shiftStore.addShift(submitData);
      ElMessage.success("新增班次成功");
    }
    dialogVisible.value = false;
  } catch (error) {
    // 这里会捕获表单验证错误和API错误
    if (error instanceof Error) {
      console.error("操作失败:", error);
    }
    // 验证错误不需要额外处理，Element Plus会自动显示错误
  }
};

const rules = reactive({
  shiftName: [
    { required: true, message: '请输入班次名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (!form.startTime || !value) {
          callback();
          return;
        }

        // 这里可以添加自定义验证逻辑
        // 例如确保结束时间不等于开始时间
        if (form.startTime === value) {
          callback(new Error('结束时间不能等于开始时间'));
          return;
        }

        callback();
      },
      trigger: 'change'
    }
  ]
});

// 删除班次
const handleDelete = (id: number) => {
  ElMessageBox.confirm("确定要删除该班次吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      console.log(id);
      await shiftStore.removeShift(id);
      ElMessage.success("删除成功");
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

// 分页变化
const handlePageChange = () => {
  shiftStore.getShifts();
};

// 每页条数变化
const handleSizeChange = () => {
  shiftStore.pagination.current = 1; // 重置到第一页
  shiftStore.getShifts();
};

// 搜索
const handleSearch = () => {
  shiftStore.pagination.current = 1;
  shiftStore.getShifts();
};
</script>

<style lang="scss" scoped>
.shifts-container {
  .header-actions {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left-section {
      display: flex;
      align-items: center;
      gap: 16px;

      h2 {
        margin: 0;
        color: #303133;
      }
    }

    .right-section {
      .search-input {
        width: 250px;

        :deep(.el-input__prefix) {
          display: flex;
          align-items: center;
          padding-left: 8px;
        }
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .total {
      margin-right: 10px;
      color: #606266;
    }
  }

  .pagination {
    display: flex;
    align-items: center;
    justify-content: flex-end;

    .page-jumper {
      display: flex;
      align-items: center;
      margin-left: 10px;

      .page-total {
        margin-left: 8px;
        color: #909399;
      }
    }

    .total {
      margin-right: 10px;
      color: #606266;
    }
  }
}
</style>